//---------------------------------------------------------------------------

#include "vcl_stl.h"
#pragma hdrstop

#include <algorithm>

#include "h_base.h"
#include "h_xml.h"
#include "h_global.h"
using namespace h_base;
using namespace h_xml;

#include "h_g.h"
#include "h_stage.h"
#include "h_server.h"
#include "h_portal.h"
#include "t_dummyform.h"
#include "t_mainform.h"
#include "t_confirmform.h"
#include "h_i18n.h"

#include "t_normaljobform.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TNormalJobForm *NormalJobForm;
TNormalJobForm *TNormalJobForm::This = NULL;
//---------------------------------------------------------------------------
__fastcall TNormalJobForm::TNormalJobForm(TComponent* Owner)
   : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TNormalJobForm::ButtonOkClick(TObject *Sender)
{
   Close();
}
//---------------------------------------------------------------------------

bool __fastcall TNormalJobForm::Edit(HStageJob *Stage, bool PartFlag)
{
   This = this;
   FStage = Stage;
   FStage->GetInfo(Info);
   UTF8String Cap;
   Cap.sprintf(UTF8String(DummyForm->PropertiesOf->Caption).c_str(), Info.Name.c_str());
   Caption = Cap;
   EditName->Text = Info.Name;
   EditCommand->Text = Info.Command;
   EditRestoreCommand->Text = Info.RestoreCommand;
   SetStringToMemo(MemoDescription, Info.Description);
   SetStringToMemo(MemoResourceList, Info.ResourceListStr);
   SetStringToMemo(MemoExternJobList, Info.ExternJobListStr);
   EditSpecialDate->Text = Info.SpecialDate;
   CheckBoxCondNot->Checked = Info.CondNot;
   EditConditionFile->Text = Info.ConditionFile;
   EditAdditionalLog->Text = Info.AdditionalLog;
   EditAlarmTimeType->Text = HStage::AlarmTimeTypeToString(Info.AlarmTimeType);
   EditAlarmTime->Text = Info.AlarmTime;
   EditJobTrigger->Text = Info.JobTrigger;
   EditPartitionFile->Text = Info.PartitionFile;
   CheckBoxExclusive->Checked = Info.Exclusive;
   EditParallelJobNumber->Text = Info.ParallelJobNumber;
   EditPriority->Text = Info.Priority;
   EditAutoRerun->Text = Info.AutoRerun;
   EditTag->Text = Info.Tag;
   EditBusinessType->Text = Info.BusinessType;
   EditRunningGroup->Text = Info.RunningGroup;
   CheckBoxAnchor->Checked = Info.Anchor;
   EditLoopStartTime->Text = Info.LoopStartTime;
   EditLoopEndTime->Text = Info.LoopEndTime;
   EditLoopInterval->Text = Info.LoopInterval;
   EditLoopCount->Text = Info.LoopCount;
   EditLoopConditionVariable->Text = Info.LoopConditionVariable;
   EditStatus->Text = Info.Status;
   EditRestoreStatus->Text = Info.RestoreStatus;
   EditStartTime->Text = FormatDateTime(Info.StartTime);
   EditEndTime->Text = FormatDateTime(Info.EndTime);
   EditElapse->Text = DiffTime(Info.StartTime, Info.EndTime, Info.IdleTimeSum);
   EditServerId->Text = ( Info.ServerId == 0 ? UTF8String("") : UTF8String(Info.ServerId) );
   EditPid->Text = ( Info.Pid == 0 ? UTF8String("") : UTF8String(Info.Pid) );

   if ( Info.PartFlag )
   {
      PartGrid->ColCount = 8;
      PartGrid->ColWidths[0] = 100;
      PartGrid->ColWidths[1] = 100;
      PartGrid->ColWidths[2] = 150;
      PartGrid->ColWidths[3] = 150;
      PartGrid->ColWidths[4] = 150;
      PartGrid->ColWidths[5] = 150;
      PartGrid->ColWidths[6] = 50;
      PartGrid->ColWidths[7] = 50;
      PartGrid->RowCount = 2;
      if ( !Info.PartMap.empty() )
      {
         PartGrid->RowCount = Info.PartMap.size() + 1;
      }
      PartGrid->Cells[0][0] = UTF8String(h_g::I18nString("t_normaljobform:PARTITION_ID"));
      PartGrid->Cells[1][0] = UTF8String(h_g::I18nString("t_normaljobform:STATUS"));
      PartGrid->Cells[2][0] = UTF8String(h_g::I18nString("t_normaljobform:RESTORE_STATUS"));
      PartGrid->Cells[3][0] = UTF8String(h_g::I18nString("t_normaljobform:START_TIME"));
      PartGrid->Cells[4][0] = UTF8String(h_g::I18nString("t_normaljobform:END_TIME"));
      PartGrid->Cells[5][0] = UTF8String(h_g::I18nString("t_normaljobform:ELAPSED"));
      PartGrid->Cells[6][0] = UTF8String(h_g::I18nString("t_normaljobform:SERVER_ID"));
      PartGrid->Cells[7][0] = UTF8String(h_g::I18nString("t_normaljobform:PROCESS_ID"));
      PartVec.clear();
      for ( map<UTF8String, HStageJob::HPartInfo>::iterator Iter = Info.PartMap.begin();
            Iter != Info.PartMap.end(); Iter++ )
      {
         HStageJob::HPartInfo &Part = Iter->second;
         Part.Elapsed = DiffTime(Part.StartTime, Part.EndTime);
         PartVec.push_back(&Part);
      }
      PartGrid->Options << goColSizing << goRowSelect >> goRangeSelect;
      if ( ComboBoxSort->ItemIndex == -1 )
      {
         ComboBoxSort->ItemIndex = 0;
      }
      TGridRect Rect;
      Rect.Left = 0;
      Rect.Top = 1;
      Rect.Right = 7;
      Rect.Bottom = 1;
      PartGrid->Selection = Rect;
      bool CanSelect = true;
      PartGridSelectCell(this, 0, 1, CanSelect);
      SortByColumn(ComboBoxSort->ItemIndex);
      TabSheet3->TabVisible = true;
   }
   else
   {
      TabSheet3->TabVisible = false;
   }

   PageControl1->ActivePageIndex = PartFlag ? 2 : 0;
   ShowModal();
   return true;
}

void __fastcall TNormalJobForm::RefreshPartInfo()
{
   HPortal *Portal = MainForm->Portal;

   Sleep(200);
   Portal->Refresh();
   Close();
}

void __fastcall TNormalJobForm::PartGridSelectCell(TObject *Sender,
      int ACol, int ARow, bool &CanSelect)
{
   if ( Info.PartMap.empty() )
   {
      ButtonSkip->Enabled = false;
      ButtonRestore->Enabled = false;
      ButtonRerun->Enabled = false;
      ButtonStop->Enabled = false;
      ButtonViewLog->Enabled = false;
      ButtonViewAdditionalLog->Enabled = false;
      ButtonSort->Enabled = false;
      return;
   }

   UTF8String PartId = CurrentPartId();

   if ( Info.PartMap.find(PartId) == Info.PartMap.end() )
   {
      return;
   }

   HStageJob::HPartInfo &Part = Info.PartMap[PartId];

   ButtonSort->Enabled = true;

   HBatchIcon *Batch = MainForm->Portal->CurrentBatch;

   if ( Batch->Outline.Offline )
   {
      ButtonSkip->Enabled = false;
      ButtonRestore->Enabled = false;
      ButtonRerun->Enabled = false;
      ButtonStop->Enabled = false;
      ButtonViewLog->Enabled = false;
      ButtonViewAdditionalLog->Enabled = false;
      ButtonViewRestoreLog->Enabled = false;
      return;
   }

   ButtonSkip->Enabled = MainForm->CurrentBatchIsRunning() &&
      ( Part.Status == "FAIL" || Part.Status == "UNKNOWN" );
   ButtonRestore->Enabled = MainForm->CurrentBatchIsRunning() &&
      ( Part.RestoreStatus == "NEED_RESTORE" );
   ButtonRerun->Enabled =  MainForm->CurrentBatchIsRunning() &&
      ( Part.Status == "FAIL" || Part.Status == "UNKNOWN" ) &&
      ( Part.RestoreStatus == "" || Part.RestoreStatus == "RESTORED" );
   ButtonStop->Enabled = MainForm->CurrentBatchIsRunning() &&
      ( Part.Status == "RUNNING" );
   ButtonViewLog->Enabled = Part.StartTime != "";
   ButtonViewAdditionalLog->Enabled = Part.StartTime != "" && Info.AdditionalLog != "";
}
//---------------------------------------------------------------------------

UTF8String __fastcall TNormalJobForm::CurrentPartId()
{
   int ARow = PartGrid->Selection.Top;

   if ( ARow <= PartVec.size() )
   {
      return PartVec[ARow - 1]->Id;
   }
   else
   {
      return "";
   }
}

void __fastcall TNormalJobForm::ButtonSkipClick(TObject *Sender)
{
   HPortal *Portal = MainForm->Portal;
   HStage *SelectedStage = FStage;
   UTF8String JobName = SelectedStage->GetGroupId() + h_g::JobNameDelimiter +
      SelectedStage->GetName() + h_g::JobNameDelimiter + CurrentPartId();
   UTF8String ErrorString;

   char TmpStr[500 + 1];
   snprintf(TmpStr, 500, h_g::I18nString("t_normaljobform:SKIP_JOB"),
      JobName.c_str());

   if ( !ConfirmForm->Confirm(Portal->CurrentBatch, TmpStr, "skip_job") )
   {
      return;
   }

   if( HServer::FuncSkipJob(Portal->CurrentBatch, JobName, ErrorString) )
   {
      RefreshPartInfo();
   }
   else
      h_g::ShowMessage(ErrorString);
}
//---------------------------------------------------------------------------

void __fastcall TNormalJobForm::ButtonRestoreClick(TObject *Sender)
{
   HPortal *Portal = MainForm->Portal;
   HStage *SelectedStage = FStage;
   UTF8String JobName = SelectedStage->GetGroupId() + h_g::JobNameDelimiter +
      SelectedStage->GetName() + h_g::JobNameDelimiter + CurrentPartId();
   UTF8String ErrorString;

   char TmpStr[500 + 1];
   snprintf(TmpStr, 500, h_g::I18nString("t_normaljobform:RESTORE_JOB"),
      JobName.c_str());

   if ( !ConfirmForm->Confirm(Portal->CurrentBatch, TmpStr, "restore_job") )
   {
      return;
   }

   if( HServer::FuncRestoreJob(Portal->CurrentBatch, JobName, ErrorString) )
   {
      RefreshPartInfo();
   }
   else
      h_g::ShowMessage(ErrorString);
}
//---------------------------------------------------------------------------

void __fastcall TNormalJobForm::ButtonRerunClick(TObject *Sender)
{
   HPortal *Portal = MainForm->Portal;
   HStage *SelectedStage = FStage;
   UTF8String JobName = SelectedStage->GetGroupId() + h_g::JobNameDelimiter +
      SelectedStage->GetName() + h_g::JobNameDelimiter + CurrentPartId();
   UTF8String ErrorString;

   char TmpStr[500 + 1];
   snprintf(TmpStr, 500, h_g::I18nString("t_normaljobform:RERUN_JOB"),
      JobName.c_str());

   if ( !ConfirmForm->Confirm(Portal->CurrentBatch, TmpStr, "rerun_job") )
   {
      return;
   }

   if( HServer::FuncRerunJob(Portal->CurrentBatch, JobName, ErrorString) )
   {
      RefreshPartInfo();
   }
   else
      h_g::ShowMessage(ErrorString);

}
//---------------------------------------------------------------------------

void __fastcall TNormalJobForm::ButtonStopClick(TObject *Sender)
{
   HPortal *Portal = MainForm->Portal;
   HStage *SelectedStage = FStage;
   UTF8String JobName = SelectedStage->GetGroupId() + h_g::JobNameDelimiter +
      SelectedStage->GetName() + h_g::JobNameDelimiter + CurrentPartId();
   UTF8String ErrorString;

   char TmpStr[500 + 1];
   snprintf(TmpStr, 500, h_g::I18nString("t_normaljobform:STOP_JOB"),
      JobName.c_str());

   if ( !ConfirmForm->Confirm(Portal->CurrentBatch, TmpStr, "stop_job") )
   {
      return;
   }

   if( HServer::FuncStopJob(Portal->CurrentBatch, JobName, ErrorString) )
   {
      RefreshPartInfo();
   }
   else
      h_g::ShowMessage(ErrorString);
}
//---------------------------------------------------------------------------

void __fastcall TNormalJobForm::ButtonViewLogClick(TObject *Sender)
{
   HPortal *Portal = MainForm->Portal;
   HStage *SelectedStage = FStage;
   UTF8String JobName = SelectedStage->GetGroupId() + h_g::JobNameDelimiter +
      SelectedStage->GetName() + h_g::JobNameDelimiter + CurrentPartId();

   HServer::FuncViewLog(Portal->CurrentBatch, JobName);
}
//---------------------------------------------------------------------------

void __fastcall TNormalJobForm::ButtonViewAdditionalLogClick(
      TObject *Sender)
{
   HPortal *Portal = MainForm->Portal;
   HStage *SelectedStage = FStage;
   UTF8String JobName = SelectedStage->GetGroupId() + h_g::JobNameDelimiter +
      SelectedStage->GetName() + h_g::JobNameDelimiter + CurrentPartId();

   HServer::FuncViewAdditionalLog(Portal->CurrentBatch, JobName);
}
//---------------------------------------------------------------------------

bool __fastcall TNormalJobForm::Compare0(const HStageJob::HPartInfo *lhs, const HStageJob::HPartInfo *rhs)
{
   const HStageJob::HPartInfo &PartLeft = *lhs;
   const HStageJob::HPartInfo &PartRight = *rhs;

   return PartLeft.Id < PartRight.Id;
}

bool __fastcall TNormalJobForm::Compare1(const HStageJob::HPartInfo *lhs, const HStageJob::HPartInfo *rhs)
{
   const HStageJob::HPartInfo &PartLeft = *lhs;
   const HStageJob::HPartInfo &PartRight = *rhs;

   if ( PartLeft.StatusInt == PartRight.StatusInt )
   {
      return PartLeft.Id < PartRight.Id;
   }

   return PartLeft.StatusInt < PartRight.StatusInt;
}

bool __fastcall TNormalJobForm::Compare2(const HStageJob::HPartInfo *lhs, const HStageJob::HPartInfo *rhs)
{
   const HStageJob::HPartInfo &PartLeft = *lhs;
   const HStageJob::HPartInfo &PartRight = *rhs;

   if ( PartLeft.RestoreStatus == PartRight.RestoreStatus )
   {
      return PartLeft.Id < PartRight.Id;
   }

   return PartLeft.RestoreStatus < PartRight.RestoreStatus;
}

bool __fastcall TNormalJobForm::Compare3(const HStageJob::HPartInfo *lhs, const HStageJob::HPartInfo *rhs)
{
   const HStageJob::HPartInfo &PartLeft = *lhs;
   const HStageJob::HPartInfo &PartRight = *rhs;

   if ( PartLeft.StartTime == PartRight.StartTime )
   {
      return PartLeft.Id < PartRight.Id;
   }

   return PartLeft.StartTime < PartRight.StartTime;
}

bool __fastcall TNormalJobForm::Compare4(const HStageJob::HPartInfo *lhs, const HStageJob::HPartInfo *rhs)
{
   const HStageJob::HPartInfo &PartLeft = *lhs;
   const HStageJob::HPartInfo &PartRight = *rhs;

   if ( PartLeft.EndTime == PartRight.EndTime )
   {
      return PartLeft.Id < PartRight.Id;
   }

   return PartLeft.EndTime < PartRight.EndTime;
}

bool __fastcall TNormalJobForm::Compare5(const HStageJob::HPartInfo *lhs, const HStageJob::HPartInfo *rhs)
{
   const HStageJob::HPartInfo &PartLeft = *lhs;
   const HStageJob::HPartInfo &PartRight = *rhs;

   if ( PartLeft.ServerId == PartRight.ServerId )
   {
      return PartLeft.Id < PartRight.Id;
   }

   return PartLeft.ServerId < PartRight.ServerId;
}

bool __fastcall TNormalJobForm::Compare6(const HStageJob::HPartInfo *lhs, const HStageJob::HPartInfo *rhs)
{
   const HStageJob::HPartInfo &PartLeft = *lhs;
   const HStageJob::HPartInfo &PartRight = *rhs;

   if ( PartLeft.Pid == PartRight.Pid )
   {
      return PartLeft.Id < PartRight.Id;
   }

   return PartLeft.Pid < PartRight.Pid;
}

bool __fastcall TNormalJobForm::Compare7(const HStageJob::HPartInfo *lhs, const HStageJob::HPartInfo *rhs)
{
   const HStageJob::HPartInfo &PartLeft = *lhs;
   const HStageJob::HPartInfo &PartRight = *rhs;

   if ( PartLeft.Elapsed == PartRight.Elapsed )
   {
      return PartLeft.Id < PartRight.Id;
   }

   return PartLeft.Elapsed < PartRight.Elapsed;
}

void __fastcall TNormalJobForm::ButtonSortClick(TObject *Sender)
{
   SortByColumn(ComboBoxSort->ItemIndex);
}
//---------------------------------------------------------------------------

void __fastcall TNormalJobForm::SortByColumn(int Index)
{
   UTF8String PartId = CurrentPartId();

   switch ( Index )
   {
   case 0 :
      sort(PartVec.begin(), PartVec.end(), Compare0);
      break;
   case 1 :
      sort(PartVec.begin(), PartVec.end(), Compare1);
      break;
   case 2 :
      sort(PartVec.begin(), PartVec.end(), Compare2);
      break;
   case 3 :
      sort(PartVec.begin(), PartVec.end(), Compare3);
      break;
   case 4 :
      sort(PartVec.begin(), PartVec.end(), Compare4);
      break;
   case 5 :
      sort(PartVec.begin(), PartVec.end(), Compare5);
      break;
   case 6 :
      sort(PartVec.begin(), PartVec.end(), Compare6);
      break;
   case 7 :
      sort(PartVec.begin(), PartVec.end(), Compare7);
      break;
   }

   int i;

   for ( i = 0; i < PartVec.size(); i++ )
   {
      HStageJob::HPartInfo &Part = *PartVec[i];
      TStrings *Strings = new TStringList();
      Strings->Add(Part.Id);
      Strings->Add(Part.Status);
      Strings->Add(Part.RestoreStatus);
      Strings->Add(FormatDateTime(Part.StartTime));
      Strings->Add(FormatDateTime(Part.EndTime));
      Strings->Add(Part.Elapsed);
      Strings->Add(UTF8String(Part.ServerId));
      Strings->Add(UTF8String(Part.Pid));
      PartGrid->Rows[i + 1] = Strings;
      delete Strings;
   }

   for ( i = 0; i < PartVec.size(); i++ )
   {
      if ( PartId == PartVec[i]->Id )
      {
         break;
      }
   }

   TGridRect Rect;

   if ( i == PartVec.size() )
   {
      i = 0;
   }

   Rect.Left = 0;
   Rect.Top = i + 1;
   Rect.Right = 6;
   Rect.Bottom = Rect.Top;
   PartGrid->Selection = Rect;
}

void __fastcall TNormalJobForm::ButtonViewRestoreLogClick(TObject *Sender)
{
   HPortal *Portal = MainForm->Portal;
   HStage *SelectedStage = FStage;
   UTF8String JobName = SelectedStage->GetGroupId() + h_g::JobNameDelimiter +
      SelectedStage->GetName() + h_g::JobNameDelimiter + CurrentPartId();

   HServer::FuncViewLog(Portal->CurrentBatch, JobName, true);

}
//---------------------------------------------------------------------------

